package com.hoangkien.soundcloud.activity;

import static android.view.Gravity.START;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.graphics.drawable.TransitionDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.DrawerLayout.DrawerListener;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.util.TypedValue;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewTreeObserver.OnDrawListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;

import com.astuetz.PagerSlidingTabStrip;
import com.hoangkien.apdater.AdapterMenuTab;
import com.hoangkien.config.SoundCloudConfig;
import com.hoangkien.fragment.AllSoundCloudFragment;
import com.hoangkien.fragment.DownloadFragment;
import com.hoangkien.fragment.HistoryFragment;
import com.hoangkien.fragment.PlayListFragment;
import com.hoangkien.service.SoundCloudService;
import com.hoangkien.service.UserService;
import com.hoangkien.soundcloud.R;
import com.hoangkien.soundcloud.widget.CustomEditText;
import com.hoangkien.soundcloud.widget.DrawerArrowDrawable;
import com.hoangkien.soundcloud.widget.IPopupWindow;
import com.hoangkien.soundcloud.widget.config.DrawableClickListener;
import com.hoangkien.util.SoundCloudSharePreference;
import com.sothree.slidinguppanel.SlidingUpPanelLayout;
import com.sound.service.GetDataCloud;

@SuppressLint("NewApi")
public class MainActivity extends FragmentActivity implements OnClickListener, OnTouchListener, DrawableClickListener{
	private static final String TAG = "MainActivity";
	public static final String SAVED_STATE_ACTION_BAR_HIDDEN = "saved_state_action_bar_hidden";
	private final Handler handler = new Handler();

	private SlidingUpPanelLayout mLayout;
	private ListView lvSlideMenuLeft;
	private PagerSlidingTabStrip tabs;
	private ViewPager pager;
	private MyPagerAdapter adapter;
	private int currentColor = 0xFF666666;
	private Drawable oldBackground = null;

	private DrawerLayout drawer;
	private ActionBarDrawerToggle mDrawerToggle;
	private DrawerArrowDrawable drawerArrowDrawable;
	private ImageView img_actionbar_open_close_drawer;
	private float offset;
	private boolean flipped;
	private ImageView ivSearch;
	private ProgressBar pbRefesh;
	private ImageView ivRefesh;
	private ImageView ivRefresh;
	private CustomEditText etSearch;

	private GetDataCloud get;
	private UserService userService;
	private SoundCloudService soundCloudService;
	private SoundCloudSharePreference preference;
	private IPopupWindow popupSortby;
	
	private Handler handlerRefresh;

	public static String[] genresTitle = new String[] { "genres",
			"		Alternative Rock", "		Ambient", "		Classical", "		Country",
			"		Dance", "		Deep House", "		Disco", "		Drum & Bass", "		Dubstep",
			"		Electro", "		Electronic", "		Folk", "		Hardcore Techno",
			"		Hip Hop", "		House", "		Indie Rock", "		Jazz", "		Latin",
			"		Metal", "		Minimal Techno", "		Piano", "		Pop",
			"		Progressive House", "		Punk", "		R & B", "		Rap", "		Reggae",
			"		Rock", "		Soul", "		Tech House", "		Techno", "		Trance",
			"		Trap", "		Trip Hop", "		World" };

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_layout);
		getActionBar().hide();
		preference = new SoundCloudSharePreference(MainActivity.this);
		drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
		mLayout = (SlidingUpPanelLayout) findViewById(R.id.sliding_layout);
		lvSlideMenuLeft = (ListView) findViewById(R.id.list_slidermenu);

		img_actionbar_open_close_drawer = (ImageView) findViewById(R.id.drawer_indicator);  //mui ten open || close drawer
		img_actionbar_open_close_drawer.setOnClickListener(this);
		img_actionbar_open_close_drawer.setOnTouchListener(this);
		final Resources resources = getResources();
		drawerArrowDrawable = new DrawerArrowDrawable(resources);
		drawerArrowDrawable.setStrokeColor(resources.getColor(R.color.light_gray));
		img_actionbar_open_close_drawer.setImageDrawable(drawerArrowDrawable);
		drawer.setDrawerListener(new DrawerLayout.SimpleDrawerListener() {
			@Override
			public void onDrawerSlide(View drawerView, float slideOffset) {
				offset = slideOffset;
				if (slideOffset >= .995) {
					flipped = true;
					drawerArrowDrawable.setFlip(flipped);
				} else if (slideOffset <= .005) {
					flipped = false;
					drawerArrowDrawable.setFlip(flipped);
				}
				drawerArrowDrawable.setParameter(offset);
			}
		});
		ivSearch = (ImageView) findViewById(R.id.isearch);
		ivSearch.setOnClickListener(this);
		pbRefesh = (ProgressBar) findViewById(R.id.pbrefesh);
		etSearch = (CustomEditText) findViewById(R.id.etsearch);
		etSearch.setDrawableClickListener(this);
		ivRefresh = (ImageView) findViewById(R.id.ivrefesh);
		ivRefresh.setOnClickListener(this);
		
		handlerRefresh = new Handler(){
			@Override
			public void handleMessage(Message msg) {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {}
				ivRefresh.setVisibility(View.VISIBLE);
				pbRefesh.setVisibility(View.GONE);
			}
		};

		
		mLayout.hidePanel();

		// Adapter cho menu left
		AdapterMenuTab adapterMenuLeft = new AdapterMenuTab(MainActivity.this,genresTitle);
		lvSlideMenuLeft.setAdapter(adapterMenuLeft);

		// phan tabtrip content
		tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
		pager = (ViewPager) findViewById(R.id.pager);
		adapter = new MyPagerAdapter(getSupportFragmentManager());
		pager.setAdapter(adapter);
		final int pageMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getResources().getDisplayMetrics());
		pager.setPageMargin(pageMargin);
		tabs.setViewPager(pager);
		changeColor(currentColor);

		// database
		userService = new UserService(MainActivity.this);
		soundCloudService = new SoundCloudService(MainActivity.this);

		 if(userService.getAllUser().size() == 0 &&  soundCloudService.getAllSoundCloud().size() == 0) { //get data insert database
			 get = new GetDataCloud(MainActivity.this, 10, 0, "");
			 get.execute();
		 }
	}
	
	private void getDataSpinner(final String[] values, final EditText editText) {
		popupSortby = new IPopupWindow(this, R.layout.popup_sortby_layout,null, false, editText.getMeasuredWidth(),LayoutParams.WRAP_CONTENT);
		ListView listPopup = (ListView) popupSortby.getView().findViewById(R.id.listPopup);
		if (values != null && values.length != 0) {
			ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,R.layout.spinner_adapter, values);
			listPopup.setAdapter(adapter);
		}
		listPopup.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				editText.setText(values[position].toString());
				popupSortby.dismiss();
			}
		});
		popupSortby.setAutoHideOutside();
		popupSortby.showAsDropDown(editText);
	}
	
	@Override
	public void onClick(DrawablePosition target) {
		if (target == DrawablePosition.RIGHT) {
			String[] arr = new String[]{"fjasdf","dấdfgdfhgh"};
			getDataSpinner(arr, etSearch);
		}
		if (target == DrawablePosition.LEFT) {
			etSearch.setVisibility(View.GONE);
			ivSearch.setVisibility(View.VISIBLE);
		}
	}
	
	@Override
	public boolean onTouch(View v, MotionEvent event) {
		switch (v.getId()) {
		case R.id.drawer_indicator:
			int eventaction = event.getAction();
			switch (eventaction) {
			case MotionEvent.ACTION_DOWN:
				img_actionbar_open_close_drawer.setBackgroundResource(0);
				break;
			default:
				break;
			}
			break;
		default:
			break;
		}
		return false;
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.search:

			break;
		case R.id.pbrefesh:

			break;
		case R.id.isearch:
			etSearch.setVisibility(View.VISIBLE);
			ivSearch.setVisibility(View.GONE);
			break;
		case R.id.ivrefesh:
			etSearch.setVisibility(View.GONE);
			ivSearch.setVisibility(View.VISIBLE);
			ivRefresh.setVisibility(View.GONE);
			pbRefesh.setVisibility(View.VISIBLE);
			Intent intent = new Intent(SoundCloudConfig.BROADCAST_REFRESH_DATA);
			sendBroadcast(intent);
			handlerRefresh.sendEmptyMessage(0);
			break;
		case R.id.drawer_indicator:
			if (drawer.isDrawerVisible(START)) {
				drawer.closeDrawer(START);
			} else {
				drawer.openDrawer(START);
			}
			break;

		default:
			break;
		}
	}

	@SuppressLint("NewApi")
	private void changeColor(int newColor) {

		tabs.setIndicatorColor(newColor);
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			Drawable colorDrawable = new ColorDrawable(newColor);
			Drawable bottomDrawable = getResources().getDrawable(R.drawable.actionbar_bottom);
			LayerDrawable ld = new LayerDrawable(new Drawable[] {colorDrawable, bottomDrawable });

			if (oldBackground == null) {
				if (Build.VERSION.SDK_INT < Build.VERSION_CODES.BASE) {
					ld.setCallback(drawableCallback);
				} else {
					getActionBar().setBackgroundDrawable(ld);
				}

			} else {

				TransitionDrawable td = new TransitionDrawable(new Drawable[] { oldBackground, ld });
				if (Build.VERSION.SDK_INT < Build.VERSION_CODES.BASE) {
					td.setCallback(drawableCallback);
				} else {
					getActionBar().setBackgroundDrawable(td);
				}

				td.startTransition(200);

			}

			oldBackground = ld;
		}

		currentColor = newColor;

	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putBoolean(SAVED_STATE_ACTION_BAR_HIDDEN, mLayout.isPanelExpanded());
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public void onBackPressed() {
		if (mLayout != null && mLayout.isPanelExpanded() || mLayout.isPanelAnchored()) {
			mLayout.collapsePanel();
		} else {
			super.onBackPressed();
		}
	}

	private Drawable.Callback drawableCallback = new Drawable.Callback() {
		@SuppressLint("NewApi")
		@Override
		public void invalidateDrawable(Drawable who) {
			getActionBar().setBackgroundDrawable(who);
		}

		@Override
		public void scheduleDrawable(Drawable who, Runnable what, long when) {
			handler.postAtTime(what, when);
		}

		@Override
		public void unscheduleDrawable(Drawable who, Runnable what) {
			handler.removeCallbacks(what);
		}
	};

	public class MyPagerAdapter extends FragmentPagerAdapter {

		private final String[] TITLES = { "all", "playlist", "history", "download" };

		public MyPagerAdapter(FragmentManager fm) {
			super(fm);
		}

		@Override
		public CharSequence getPageTitle(int position) {
			return TITLES[position];
		}

		@Override
		public int getCount() {
			return TITLES.length;
		}

		@Override
		public Fragment getItem(int position) {
			switch (position) {
			case 0:
				return AllSoundCloudFragment.newInstance(position);
			case 1:
				return PlayListFragment.newInstance(position);
			case 2:
				return HistoryFragment.newInstance(position);
			case 3:
				return DownloadFragment.newInstance(position);
			}
			return PlayListFragment.newInstance(position);
		}
	}


}
